<template>
  <div class="image-detection">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>AI图像检测</h1>
      <p>专业的AI生成图像识别与分析</p>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section">
      <div class="upload-container">
        <div 
          class="upload-area"
          @dragover.prevent
          @drop="handleDrop"
          :class="{ 'drag-over': isDragOver }"
        >
          <div class="upload-icon">📸</div>
          <h3>上传图像进行检测</h3>
          <p>支持 JPG, PNG, GIF 格式，最大 10MB</p>
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            @change="handleFileUpload"
            multiple
            style="display: none;"
          />
          <button class="upload-btn" @click="$refs.fileInput.click()">
            选择图像
          </button>
        </div>
        
        <div class="batch-controls">
          <button 
            class="batch-btn"
            @click="enableBatchMode"
            :class="{ active: batchMode }"
          >
            批量检测
          </button>
          <button class="clear-btn" @click="clearImages">
            清空列表
          </button>
        </div>
      </div>
    </div>

    <!-- 图像列表 -->
    <div v-if="images.length > 0" class="images-section">
      <h2>检测队列 ({{ images.length }})</h2>
      <div class="images-grid">
        <div 
          v-for="(image, index) in images" 
          :key="index"
          class="image-card"
          :class="{ 'processing': image.processing, 'completed': image.result }"
        >
          <div class="image-preview">
            <img :src="image.preview" alt="预览图" />
            <div class="image-overlay">
              <button class="remove-btn" @click="removeImage(index)">×</button>
            </div>
          </div>
          
          <div class="image-info">
            <h4>{{ image.name }}</h4>
            <p>{{ formatFileSize(image.size) }}</p>
            
            <div v-if="image.processing" class="processing-indicator">
              <div class="loading-spinner"></div>
              <span>检测中...</span>
            </div>
            
            <div v-if="image.result" class="result-summary">
              <div class="confidence-bar">
                <div 
                  class="confidence-fill"
                  :style="{ width: image.result.confidence + '%' }"
                  :class="getConfidenceClass(image.result.confidence)"
                ></div>
              </div>
              <div class="result-text">
                <span class="result-label">AI生成概率：</span>
                <span class="result-value">{{ image.result.confidence }}%</span>
              </div>
              <button class="detail-btn" @click="showDetails(image)">
                查看详情
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="batch-actions">
        <button 
          class="process-btn"
          @click="processAll"
          :disabled="processing"
        >
          {{ processing ? '处理中...' : '开始检测' }}
        </button>
        <button class="export-btn" @click="exportResults">
          导出结果
        </button>
      </div>
    </div>

    <!-- 详细分析 -->
    <div v-if="selectedImage" class="analysis-section">
      <div class="analysis-header">
        <h2>详细分析</h2>
        <button class="close-analysis" @click="selectedImage = null">×</button>
      </div>
      
      <div class="analysis-content">
        <div class="analysis-left">
          <img :src="selectedImage.preview" alt="分析图像" class="analysis-image" />
          
          <div class="image-properties">
            <h3>图像属性</h3>
            <div class="property-grid">
              <div class="property-item">
                <span class="label">尺寸：</span>
                <span class="value">{{ selectedImage.result.dimensions }}</span>
              </div>
              <div class="property-item">
                <span class="label">格式：</span>
                <span class="value">{{ selectedImage.result.format }}</span>
              </div>
              <div class="property-item">
                <span class="label">色彩空间：</span>
                <span class="value">{{ selectedImage.result.colorSpace }}</span>
              </div>
              <div class="property-item">
                <span class="label">压缩率：</span>
                <span class="value">{{ selectedImage.result.compression }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="analysis-right">
          <div class="detection-result">
            <div class="result-header">
              <h3>检测结果</h3>
              <div class="confidence-score">
                <div class="score-circle" :class="getConfidenceClass(selectedImage.result.confidence)">
                  {{ selectedImage.result.confidence }}%
                </div>
              </div>
            </div>
            
            <div class="result-details">
              <div class="detail-row">
                <span class="label">检测模型：</span>
                <span class="value">{{ selectedImage.result.model }}</span>
              </div>
              <div class="detail-row">
                <span class="label">处理时间：</span>
                <span class="value">{{ selectedImage.result.processingTime }}</span>
              </div>
              <div class="detail-row">
                <span class="label">可能的生成器：</span>
                <span class="value">{{ selectedImage.result.generator }}</span>
              </div>
            </div>
          </div>
          
          <div class="technical-analysis">
            <h3>技术分析</h3>
            <div class="analysis-metrics">
              <div class="metric-item">
                <span class="metric-label">像素一致性：</span>
                <div class="metric-bar">
                  <div 
                    class="metric-fill"
                    :style="{ width: selectedImage.result.pixelConsistency + '%' }"
                  ></div>
                </div>
                <span class="metric-value">{{ selectedImage.result.pixelConsistency }}%</span>
              </div>
              
              <div class="metric-item">
                <span class="metric-label">频域特征：</span>
                <div class="metric-bar">
                  <div 
                    class="metric-fill"
                    :style="{ width: selectedImage.result.frequencyFeatures + '%' }"
                  ></div>
                </div>
                <span class="metric-value">{{ selectedImage.result.frequencyFeatures }}%</span>
              </div>
              
              <div class="metric-item">
                <span class="metric-label">纹理分析：</span>
                <div class="metric-bar">
                  <div 
                    class="metric-fill"
                    :style="{ width: selectedImage.result.textureAnalysis + '%' }"
                  ></div>
                </div>
                <span class="metric-value">{{ selectedImage.result.textureAnalysis }}%</span>
              </div>
            </div>
          </div>
          
          <div class="warning-signs">
            <h3>检测特征</h3>
            <div class="signs-list">
              <div 
                v-for="sign in selectedImage.result.signs" 
                :key="sign.name"
                class="sign-item"
                :class="sign.level"
              >
                <div class="sign-icon">{{ sign.icon }}</div>
                <div class="sign-content">
                  <div class="sign-name">{{ sign.name }}</div>
                  <div class="sign-desc">{{ sign.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 检测历史 -->
    <div class="history-section">
      <h2>检测历史</h2>
      <div class="history-controls">
        <input 
          v-model="historySearch"
          placeholder="搜索历史记录..."
          class="search-input"
        />
        <select v-model="historyFilter" class="filter-select">
          <option value="">全部结果</option>
          <option value="ai">AI生成</option>
          <option value="human">人类创作</option>
        </select>
      </div>
      
      <div class="history-list">
        <div 
          v-for="record in filteredHistory" 
          :key="record.id"
          class="history-item"
        >
          <div class="history-preview">
            <img :src="record.preview" alt="历史图像" />
          </div>
          <div class="history-info">
            <h4>{{ record.name }}</h4>
            <p>{{ record.date }}</p>
            <div class="history-result">
              <span class="result-badge" :class="record.resultType">
                {{ record.resultLabel }}
              </span>
              <span class="confidence">{{ record.confidence }}%</span>
            </div>
          </div>
          <div class="history-actions">
            <button class="reanalyze-btn" @click="reanalyze(record)">
              重新分析
            </button>
            <button class="delete-btn" @click="deleteHistory(record.id)">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const images = ref([])
const selectedImage = ref(null)
const batchMode = ref(false)
const processing = ref(false)
const isDragOver = ref(false)
const historySearch = ref('')
const historyFilter = ref('')

// 检测历史
const detectionHistory = ref([
  {
    id: 1,
    name: '风景照片.jpg',
    date: '2024-01-15 14:30',
    preview: '',
    resultType: 'ai',
    resultLabel: 'AI生成',
    confidence: 92
  },
  {
    id: 2,
    name: '人物头像.png',
    date: '2024-01-15 14:25',
    preview: '',
    resultType: 'human',
    resultLabel: '人类创作',
    confidence: 78
  }
])

// 计算属性
const filteredHistory = computed(() => {
  let filtered = detectionHistory.value
  
  if (historySearch.value) {
    filtered = filtered.filter(record => 
      record.name.toLowerCase().includes(historySearch.value.toLowerCase())
    )
  }
  
  if (historyFilter.value) {
    filtered = filtered.filter(record => record.resultType === historyFilter.value)
  }
  
  return filtered
})

// 方法
const handleDrop = (e) => {
  e.preventDefault()
  isDragOver.value = false
  const files = Array.from(e.dataTransfer.files)
  processFiles(files)
}

const handleFileUpload = (e) => {
  const files = Array.from(e.target.files)
  processFiles(files)
}

const processFiles = (files) => {
  files.forEach(file => {
    if (file.type.startsWith('image/')) {
      const reader = new FileReader()
      reader.onload = (e) => {
        images.value.push({
          name: file.name,
          size: file.size,
          preview: e.target.result,
          processing: false,
          result: null
        })
      }
      reader.readAsDataURL(file)
    }
  })
}

const removeImage = (index) => {
  images.value.splice(index, 1)
}

const clearImages = () => {
  images.value = []
}

const enableBatchMode = () => {
  batchMode.value = !batchMode.value
}

const processAll = async () => {
  processing.value = true
  
  for (let i = 0; i < images.value.length; i++) {
    if (!images.value[i].result) {
      images.value[i].processing = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      images.value[i].processing = false
      images.value[i].result = generateMockResult()
    }
  }
  
  processing.value = false
}

const generateMockResult = () => {
  const confidence = Math.floor(Math.random() * 40) + 60
  return {
    confidence,
    model: 'DeepDetector v3.0',
    processingTime: (Math.random() * 2 + 0.5).toFixed(1) + 's',
    generator: confidence > 80 ? 'Midjourney' : 'Stable Diffusion',
    dimensions: '1024x1024',
    format: 'JPEG',
    colorSpace: 'sRGB',
    compression: '85%',
    pixelConsistency: Math.floor(Math.random() * 30) + 70,
    frequencyFeatures: Math.floor(Math.random() * 40) + 60,
    textureAnalysis: Math.floor(Math.random() * 35) + 65,
    signs: [
      {
        name: '像素异常',
        description: '检测到不自然的像素分布',
        level: confidence > 80 ? 'high' : 'medium',
        icon: '🔍'
      },
      {
        name: '压缩伪影',
        description: '发现AI生成图像特有的压缩模式',
        level: confidence > 70 ? 'high' : 'low',
        icon: '📊'
      }
    ]
  }
}

const showDetails = (image) => {
  selectedImage.value = image
}

const getConfidenceClass = (confidence) => {
  if (confidence >= 80) return 'high'
  if (confidence >= 60) return 'medium'
  return 'low'
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const exportResults = () => {
  const results = images.value.filter(img => img.result)
  console.log('导出结果:', results)
}

const reanalyze = (record) => {
  console.log('重新分析:', record)
}

const deleteHistory = (id) => {
  const index = detectionHistory.value.findIndex(record => record.id === id)
  if (index > -1) {
    detectionHistory.value.splice(index, 1)
  }
}
</script>

<style scoped>
.image-detection {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  background: #f8f9fa;
  min-height: 100vh;
}

/* 响应式设计 */
@media (max-width: 1600px) {
  .image-detection {
    width: 90%;
  }
}

@media (max-width: 1200px) {
  .image-detection {
    width: 95%;
  }
}

@media (max-width: 768px) {
  .image-detection {
    width: 100%;
    padding: 10px;
  }
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5em;
  color: #1e3c72;
  margin-bottom: 10px;
}

.upload-section {
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 10px;
  padding: 40px;
  text-align: center;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.upload-area:hover, .upload-area.drag-over {
  border-color: #1e3c72;
  background: #f8f9fa;
}

.upload-icon {
  font-size: 3em;
  margin-bottom: 15px;
}

.upload-btn {
  padding: 12px 30px;
  background: #1e3c72;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
}

.batch-controls {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.batch-btn {
  padding: 10px 20px;
  border: 2px solid #1e3c72;
  background: white;
  color: #1e3c72;
  border-radius: 20px;
  cursor: pointer;
}

.batch-btn.active {
  background: #1e3c72;
  color: white;
}

.clear-btn {
  padding: 10px 20px;
  border: 2px solid #dc3545;
  background: white;
  color: #dc3545;
  border-radius: 20px;
  cursor: pointer;
}

.images-section {
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.image-card {
  background: #f8f9fa;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-card:hover {
  transform: translateY(-5px);
}

.image-preview {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
}

.remove-btn {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(220,53,69,0.9);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 18px;
}

.image-info {
  padding: 15px;
}

.image-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.processing-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-top: 2px solid #1e3c72;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.confidence-bar {
  height: 8px;
  background: #eee;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.confidence-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.confidence-fill.high {
  background: #dc3545;
}

.confidence-fill.medium {
  background: #ffc107;
}

.confidence-fill.low {
  background: #28a745;
}

.result-text {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.detail-btn {
  padding: 8px 16px;
  background: #1e3c72;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.batch-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 20px;
}

.process-btn {
  padding: 12px 30px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
}

.process-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.export-btn {
  padding: 12px 30px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
}

.analysis-section {
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-analysis {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.analysis-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.analysis-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 10px;
  margin-bottom: 20px;
}

.property-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 15px;
}

.property-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.score-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2em;
  font-weight: bold;
  color: white;
}

.score-circle.high {
  background: #dc3545;
}

.score-circle.medium {
  background: #ffc107;
}

.score-circle.low {
  background: #28a745;
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.metric-label {
  width: 100px;
  font-size: 0.9em;
  color: #666;
}

.metric-bar {
  flex: 1;
  height: 8px;
  background: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.metric-fill {
  height: 100%;
  background: #1e3c72;
  transition: width 0.3s ease;
}

.metric-value {
  width: 50px;
  text-align: right;
  font-size: 0.9em;
  color: #666;
}

.signs-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sign-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
}

.sign-item.high {
  background: #ffebee;
  border-left: 4px solid #dc3545;
}

.sign-item.medium {
  background: #fff3e0;
  border-left: 4px solid #ffc107;
}

.sign-item.low {
  background: #e8f5e8;
  border-left: 4px solid #28a745;
}

.sign-icon {
  font-size: 1.5em;
}

.sign-name {
  font-weight: 500;
  color: #333;
}

.sign-desc {
  color: #666;
  font-size: 0.9em;
}

.history-section {
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.history-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.filter-select {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: white;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.history-preview {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
}

.history-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.history-info {
  flex: 1;
}

.history-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.history-result {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 5px;
}

.result-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8em;
  font-weight: 500;
}

.result-badge.ai {
  background: #ffebee;
  color: #c62828;
}

.result-badge.human {
  background: #e8f5e8;
  color: #2e7d32;
}

.confidence {
  color: #666;
  font-size: 0.9em;
}

.history-actions {
  display: flex;
  gap: 10px;
}

.reanalyze-btn {
  padding: 6px 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.delete-btn {
  padding: 6px 12px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

@media (max-width: 768px) {
  .images-grid {
    grid-template-columns: 1fr;
  }
  
  .analysis-content {
    grid-template-columns: 1fr;
  }
  
  .batch-controls {
    flex-direction: column;
    align-items: center;
  }
  
  .history-controls {
    flex-direction: column;
  }
}
</style> 